package com.learn.project2.config.typehandler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @description: pojo类成员变量-数据库表 类型转换
 * @param:  
 * @return:  
 * @author zhizhuke
 * @date: 2022-01-07 16:42
 */
@MappedTypes(Integer[].class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class IntegerArrayTypeHandler implements TypeHandler<Integer[]> {

    ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, Integer[] integers, JdbcType jdbcType) throws SQLException {
        try {
            //Integer[]-->string
            String value = objectMapper.writeValueAsString(integers);
            preparedStatement.setString(i,value);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Integer[] getResult(ResultSet resultSet, String columnName) throws SQLException {
        //String → Integer[]
        try {
            //从结果集中根据列名获得对应类的查询结果
            String result = resultSet.getString(columnName);
            //把String类型的结果封装为参数（resultMap中的property属性对应的参数）需要的类型
            return objectMapper.readValue(result, Integer[].class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return new Integer[0];
    }

    @Override
    public Integer[] getResult(ResultSet resultSet, int i) throws SQLException {
        return new Integer[0];
    }

    @Override
    public Integer[] getResult(CallableStatement callableStatement, int i) throws SQLException {
        return new Integer[0];
    }
}
